// mtk_stlreader.cpp: implementation of the CStlReader class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"

#include "stl_read_write.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CStlReader::CStlReader(const char fileName[1024])
{
	strcpy(m_fileName,fileName);
	Read(NULL);	
}
CStlReader::CStlReader()
{

}
CStlReader::~CStlReader()
{
	Clear();
}

bool CStlReader::Read(char *fileName)
{
    int i =0;
    FILE *fp;
    char strtem[6];
    char line[72];


	if (fileName != NULL)
	{
		strcpy(m_fileName,fileName);
	}
    if ( !(fp = fopen(m_fileName, ("r"))) ) 
	{
		return false;
	}
	
    fgets(strtem, 6, fp);
   if(strcmp(strtem,"solid")) 
	{
		fclose(fp);
		return false;
	}
	
	while( !feof(fp) ) 
	{
		fgets(line, 72, fp) ;
		if ( /*strstr(line , "vertex" ) != NULL ||*/ strstr(line , "facet normal" ) != NULL )
		{
			STL_TRIANGLE* p_tritem = new STL_TRIANGLE;			
			if (!p_tritem) 
			{
				fclose(fp);
				return false;
			}
			sscanf (line, "%*s%*s%f%f%f",	&(p_tritem->normal.x),
				&(p_tritem->normal.y),
				&(p_tritem->normal.z));

			fgets(line, 72, fp) ;
			fgets(line, 72, fp) ;

			sscanf (line, "%*s%f%f%f",	&(p_tritem->vertex[0].x),
										&(p_tritem->vertex[0].y),
										&(p_tritem->vertex[0].z));
			
			fgets(line, 72, fp) ;
			sscanf (line, "%*s%f%f%f",	&(p_tritem->vertex[1].x),
										&(p_tritem->vertex[1].y),
										&(p_tritem->vertex[1].z));
			
			fgets(line, 72, fp) ;
			sscanf (line, "%*s%f%f%f",	&(p_tritem->vertex[2].x),
										&(p_tritem->vertex[2].y),
										&(p_tritem->vertex[2].z));
			
			m_stlvec.push_back(p_tritem);
		}
	}

    fclose(fp);
    return true;
}



void CStlReader::Clear()
{
	int i, nsize;
	STL_TRIANGLE * ptritem;
		
	nsize = m_stlvec.size();
	for (i =0; i < nsize; i ++) 
	{
		ptritem =(STL_TRIANGLE *)m_stlvec[i];
		delete []ptritem;
//		m_stlvec.pop_back();
	}
	m_stlvec.clear();
}